<?php

class UserLogic {

	function save (&$user)
	{
		$userDao = new UserDAO();

		return $userDao->save($user) == 1;
	}

	function load ($id)
	{
		$userDao = new UserDAO();

		return $userDao->get($id);
	}

	function delete ($id)
	{
		$newsItemTypeMapDao = new NewsItemTypeMapDAO();
		foreach($newsItemTypeMapDao->findWhere("news_item_id = $id") as $newsItemTypeMap)
		{
			$newsItemTypeMapDao->delete($newsItemTypeMap);
		}

		$userDao = new UserDAO();
		$userDao->delete(new User($id));
	}

	function loadRoles ($userId)
	{
		$userRoleMapDao = new UserRoleMapDAO();

		$results = $userRoleMapDao->findWhere("user_id = $userId");
		$final = array();
		foreach ($results as $userRoleMap)
		{
			array_push($final, $userRoleMap->role);
		}

		return $final;
	}

	function saveRoles ($userId, $rolesArray)
	{
		$userRoleMapDao = new UserRoleMapDAO();

		foreach($userRoleMapDao->findWhere("user_id = $userId") as $userRole)
		{
			$userRoleMapDao->delete($userRole);
		}

		$totalAttempted = 0;
		$totalSaved = 0;
		foreach ($rolesArray as $role)
		{
			$totalAttempted++;
			$totalSaved += $userRoleMapDao->save(new UserRoleMap(0, $userId, $role));
		}

		return $totalAttempted == $totalSaved;
	}




	function findAll()
	{
		$userDao = new UserDAO();

		return $userDao->findWhere();
	}


	function findByExample($user)
	{
		$userDao = new UserDAO();

		return $userDao->findExample($user);
	}


}

?>
